#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>

using namespace std;
#define Retry_count 5

void handler(int signo)
{
    std::cout << "signo: " << signo << std::endl;
    exit(0);
}

void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " + server_ip + server_port" << std::endl;
}

// 访问server
bool visitServer(string &server_ip, uint16_t &server_port, int *cnt)
{
    // 1.创建
    string inbuffer;

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "socket error" << endl;
        return false;
    }
    bool ret = true;
    // 2.建立连接
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);

    socklen_t len;
    int n = connect(sock, (struct sockaddr *)&server, sizeof(server)); // 自动bind
    if (n < 0)
    {
        cerr << "conncet error" << endl;
        ret = false;
        goto END;
    }
    *cnt = 0;

    cout << "请选择服务：";
    getline(cin, inbuffer);
    write(sock, inbuffer.c_str(), inbuffer.size());
    
    // 通信
    while (true)
    {
        //string inbuffer;
        cout << "请输入：";
        getline(cin, inbuffer);
        if (inbuffer == "quit")
            break;
        ssize_t n = write(sock, inbuffer.c_str(), inbuffer.size());
        if (n > 0)
        {
            char buff[1024];
            ssize_t m = read(sock, buff, sizeof(buff) - 1);
            if (m > 0)
            {
                buff[m] = 0;
                cout << "输入的消息：" << buff << endl;
            }
            else if (m == 0)
            {
                break;
            }
            else
            {
                ret = false;
                goto END;
            }
        }
        else
        {
            ret = false;
            goto END;
        }
    }
END:
    close(sock);
    return ret;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    string server_ip = argv[1];
    uint16_t server_port = stoi(argv[2]);
    signal(SIGPIPE, SIG_IGN);
    int cnt = 1;
    while (cnt <= Retry_count)
    {
        bool result = visitServer(server_ip, server_port, &cnt);
        if (result)
        {
            break;
        }
        else
        {
            sleep(1);
            cout << "正在尝试重连中..." << cnt << endl;
            cnt++;
        }
    }

    return 0;
}